//
//  SSWBComposeViewController.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/2/1.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 撰写微博控制器
/**
 加载视图控制器的时候,如果XIB和控制器同名,默认的构造函数会优先加载XIB
 */
class SSWBComposeViewController: UIViewController {

    /// 文本编辑视图
    @IBOutlet weak var textView: SSWBComposeTextView!
    /// 底部工具栏
    @IBOutlet weak var toolBar: UIToolbar!
    /// 发布按钮
    @IBOutlet var sendButton: UIButton!
    /// 标题标签 - XIB里面设置换行的快捷键是按住Option + Enter
    @IBOutlet var titleLabel: UILabel!
    /// 工具栏底部约束
    @IBOutlet weak var toolBarBottomConstraint: NSLayoutConstraint!
    
    fileprivate lazy var emoticonInputView: SSEmoticonInputView? = SSEmoticonInputView.inputView { [weak self] (emoticon) in

        self?.textView.insert(emoticon: emoticon)
    }

    
    // MARK: - 生命周期
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        // 监听键盘出现、隐藏动作通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        // 关闭键盘
        textView.resignFirstResponder()
    }
    
    // MARK: - 监听方法

    /// 关闭当前视图控制器
    @objc func close() {
        dismiss(animated: true, completion: nil)
    }

    /// 发布微博
    ///
    /// - Parameter sender: 按钮
    @IBAction func postStatus(_ sender: UIButton) {
        
        // 1.获取发送给服务器的表情字符串文字
        guard let text = textView.emoticonText else {
            return
        }
        
        // 2.发布微博
        // FIXME: - 临时发布带图片的微博
        let image = UIImage(named: "icon_small_kangaroo_loading_1")
        SSWBNetworkManager.shared.postStatus(status: text, image: image) { (json, success) in
            
            print(json ?? "")
            
            let message = success ? "发布成功!" : "发布失败,稍后请重新尝试..."
            
            // 如果成功,关闭当前窗口
            if success {
                
                SVProgressHUD.showSuccess(withStatus: message)
                
                // 显示提示1秒钟后退出
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                    self.close()
                })
                
            } else {
                
                SVProgressHUD.showInfo(withStatus: message)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                    SVProgressHUD.dismiss()
                })
            }
        }
        
        
    }
    
    /// 键盘监听方法
    @objc func keyboardChanged(notification: Notification) {
        
        guard let fromValue = notification.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect else {
            return
        }
        
        print(fromValue)
        
        let offset = view.bounds.height - fromValue.origin.y
        
        toolBarBottomConstraint.constant = offset
        UIView.animate(withDuration: 0.25) {
            self.view.layoutIfNeeded()
        }
        
    }
    
    /// 切换表情键盘
    @objc func emoticonKeyboard() {
        
        // textView.inputView就是文本框的输入视图
        // 如果使用系统的默认键盘,输入视图为nil
        
        // 1.设置inputView
        textView.inputView = (textView.inputView == nil) ? emoticonInputView : nil
        
        // 2.刷新inputView
        textView.reloadInputViews()
    }
    
}

// MARK: - UITextViewDelegate
extension SSWBComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        // 如果textView有文本,发布按钮就可用
        sendButton.isEnabled = textView.hasText
    }
}

fileprivate extension SSWBComposeViewController {
    
    /// 设置UI
    func setupUI() {
        view.backgroundColor = UIColor.white
        textView.contentInset = UIEdgeInsetsMake(64, 0, toolBar.bounds.height, 0)
        textView.becomeFirstResponder()
        textView.delegate = self
        setupNav()
        setupToolbar()
    }
    
    /// 设置工具栏
    func setupToolbar() {
        
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        
        
        var items = [UIBarButtonItem]()
        // 遍历数组
        for item in itemSettings {
            
            guard let imageName = item["imageName"], let image = UIImage(named: imageName) else {
                continue
            }
            let highlightImage = UIImage(named: imageName + "_highlighted")
            let button = UIButton()
            button.setImage(image, for: .normal)
            button.setImage(highlightImage, for: .highlighted)
            button.sizeToFit()
            
            // 判断actionName
            if let actionName = item["actionName"] {
                // 给button添加监听方法
                button.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            
            // 追加按钮
            items.append(UIBarButtonItem(customView: button))
            
            // 追加弹簧
            if item == itemSettings.last! {
                break
            }
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        toolBar.items = items
    }
    
    func setupNav() {
        // 设置关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
        
        // 设置发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        sendButton.isEnabled = false
        // 设置title视图
        navigationItem.titleView = titleLabel
    }
}
